package com.yxhl.zoume.core.user.ui.fragment.mywallet;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ImageView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.yxhl.zoume.R;
import com.yxhl.zoume.common.ui.fragment.BaseFragment;
import com.yxhl.zoume.core.user.presenter.mywallet.TradeRecordsPresenter;
import com.yxhl.zoume.core.user.ui.activity.MyWalletActivity;
import com.yxhl.zoume.core.user.ui.adapter.IncomeExpensesAdapter;
import com.yxhl.zoume.core.user.ui.helper.InExPopupWindowHelper;
import com.yxhl.zoume.core.user.ui.helper.InExPopupWindowHelper.IncomeExpensesType;
import com.yxhl.zoume.core.user.view.TradeRecordsView;
import com.yxhl.zoume.data.http.model.mywallet.TradeRecordBean;
import com.yxhl.zoume.di.component.usercenter.DaggerMyWalletComponent;
import com.yxhl.zoume.di.module.ActivityModule;
import com.yxhl.zoume.utils.PromptUtils;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;


/**
 * 项目名称：Ferrari
 * Created by menggod on 16/11/3 .
 */

public class HomelistFragment extends BaseFragment implements TradeRecordsView<TradeRecordBean>,
        BaseQuickAdapter.RequestLoadMoreListener,
        SwipeRefreshLayout.OnRefreshListener {


    @BindView(R.id.rv_inex_recycle_view)
    RecyclerView mRvInexRecycleView;
    @BindView(R.id.srl_inex_swipe)
    SwipeRefreshLayout mSrlInexSwipe;
    @BindView(R.id.iv_include_refresh_no_record)
    ImageView mIvIncludeRefreshNoRecord;

    private Toolbar mToolbar;
    private InExPopupWindowHelper mPopupWindowHelper;
    private IncomeExpensesType mCurrentIncomeExpensesType = IncomeExpensesType.ALL;
    private List<TradeRecordBean> tradeRecordsList = new ArrayList<>();
    private boolean isRefreshCleanList = false;



    @Inject
    TradeRecordsPresenter mTradeRecordsPresenter;
    private MyWalletActivity mMyWalletActivity;
    private IncomeExpensesAdapter mIncomeExpensesAdapter;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initPopupWindow();
        initAdapter();
        initSwipeRefresh();
        initRecycleView();
        mTradeRecordsPresenter.attachView(this);
        mTradeRecordsPresenter.queryTradeRecords(mCurrentIncomeExpensesType.getType(), false);

    }

    @Override
    public void onResume() {
        super.onResume();
        mTradeRecordsPresenter.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        mTradeRecordsPresenter.onPause();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        MyWalletActivity activity = (MyWalletActivity) mActivity;
        activity.hideTriangleAndClickable();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mTradeRecordsPresenter.onDestroy();
    }

    public static HomelistFragment newInstance() {
        HomelistFragment fragment = new HomelistFragment();
        return fragment;
    }

    private void initPopupWindow() {
        View view = View.inflate(mActivity, R.layout.popupwindow_income_expenses, null);
        mPopupWindowHelper = new InExPopupWindowHelper(view);
        mPopupWindowHelper.initPopupWindow(1);
    }

    /**
     * 测试
     */
    private void initSwipeRefresh() {
        mSrlInexSwipe.setColorSchemeResources(
                R.color.bg_color_orange,
                R.color.bg_color_green,
                R.color.colorAccent);
        mSrlInexSwipe.setOnRefreshListener(this);
        mSrlInexSwipe.post(new Runnable() {
            @Override
            public void run() {
                if (mSrlInexSwipe != null && !mSrlInexSwipe.isRefreshing()) {
                    mSrlInexSwipe.setRefreshing(true);
                }
            }
        });
    }

    private void initAdapter() {
        mIncomeExpensesAdapter = new IncomeExpensesAdapter(new ArrayList<TradeRecordBean>());
        mIncomeExpensesAdapter.setOnLoadMoreListener(this);
    }

    private void initRecycleView() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(mActivity);
        mRvInexRecycleView.setLayoutManager(layoutManager);
        mRvInexRecycleView.setAdapter(mIncomeExpensesAdapter);
        mRvInexRecycleView.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void SimpleOnItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                TradeRecordBean tradeRecordBean = mIncomeExpensesAdapter.getData().get(i);
                getAppComponent().navigator().navigateToIncomeExpensesDetail(mActivity, tradeRecordBean);
            }
        });

    }


    @Override
    protected void initializeInjector() {
        DaggerMyWalletComponent
                .builder()
                .activityModule(new ActivityModule(mActivity))
                .appComponent(getAppComponent())
                .build()
                .inject(this);
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.fragment_inex_list;
    }

    @Override
    protected void setupToolBar() {
        MyWalletActivity activity = (MyWalletActivity) getActivity();
        activity.setToolbarTitle("收支明细");
        mToolbar = activity.getToolbar();
    }

    public void showPopupWindow() {
        mPopupWindowHelper.setCurrentInexType(mCurrentIncomeExpensesType);
        mPopupWindowHelper.showAsDropDown(mToolbar);
        mPopupWindowHelper.setOnInExTypeChangeLinstener(new InExPopupWindowHelper.InExChangeListener() {
            @Override
            public void inExTypeChanger(IncomeExpensesType incomeExpensesType) {
                if (mCurrentIncomeExpensesType != incomeExpensesType) {
                    mCurrentIncomeExpensesType = incomeExpensesType;
                    tradeRecordsList.clear();
                    mTradeRecordsPresenter.queryTradeRecords(mCurrentIncomeExpensesType.getType(), false);
                }
            }

            @Override
            public void popupWindowClose() {
                mMyWalletActivity = (MyWalletActivity) getActivity();
                mMyWalletActivity.triangleAnimationEnd();
            }
        });
    }


    @Override
    public void renderTradeRecordsOnSuccess(List<TradeRecordBean> recordsList) {

        if (isRefreshCleanList) {
            tradeRecordsList.clear();
            isRefreshCleanList = false;
            PromptUtils.showShort(mActivity, "刷新完成");
        }


        tradeRecordsList.addAll(recordsList);
        mIncomeExpensesAdapter.setNewData(tradeRecordsList);

        int size = mIncomeExpensesAdapter.getData().size();
        if (size==0){
            mIvIncludeRefreshNoRecord.setVisibility(View.VISIBLE);
        }else{
            mIvIncludeRefreshNoRecord.setVisibility(View.INVISIBLE);
        }
        if (recordsList.size() < 15) {
            mIncomeExpensesAdapter.loadMoreEnd();
        } else {
            mIncomeExpensesAdapter.loadMoreComplete();

        }


        resetViewControlStatus();
        stopRefresh();


    }

    @Override
    public void renderTradeRecordsOnFailure(String errorMessage) {
        mIncomeExpensesAdapter.loadMoreFail();
        resetViewControlStatus();
        PromptUtils.showShort(mActivity, errorMessage);
    }

    @Override
    public void renderTradeRecordsOnError() {
        resetViewControlStatus();
    }

    @Override
    public void onRefresh() {
        setViewControlIsRefresh(true);
        isRefreshCleanList = true;
        startRefresh();
        mTradeRecordsPresenter.queryTradeRecords(mCurrentIncomeExpensesType.getType(), true);
    }

    @Override
    public void onLoadMoreRequested() {
        mTradeRecordsPresenter.queryTradeRecords(mCurrentIncomeExpensesType.getType(), false);

    }

    private void setViewControlIsRefresh(boolean isRefresh) {
        if (isRefresh) {
            mIncomeExpensesAdapter.setEnableLoadMore(false);
            mSrlInexSwipe.setEnabled(true);
        } else {
            mIncomeExpensesAdapter.setEnableLoadMore(true);
            mSrlInexSwipe.setEnabled(false);
        }
    }

    private void resetViewControlStatus() {
        mIncomeExpensesAdapter.setEnableLoadMore(true);
        mSrlInexSwipe.setEnabled(true);
        stopRefresh();
    }

    private void startRefresh() {
        if (mSrlInexSwipe != null && mSrlInexSwipe.isRefreshing()) {
            mSrlInexSwipe.setRefreshing(true);
        }
    }

    private void stopRefresh() {
        if (mSrlInexSwipe != null && mSrlInexSwipe.isRefreshing()) {
            mSrlInexSwipe.setRefreshing(false);
        }
    }
}
